﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;

// Downloaded from: http://www.codeproject.com/Articles/24920/C-Image-Download

namespace SharpLogic.GeeksWithBlogsToBlogML {
    public class DownloadImage {
        private string imageUrl;
        private Bitmap bitmap;
        public DownloadImage(string imageUrl) {
            this.imageUrl = imageUrl;
        }
        public void Download() {
            try {
                WebClient client = new WebClient();
                Stream stream = client.OpenRead(imageUrl);
                bitmap = new Bitmap(stream);
                stream.Flush();
                stream.Close();
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
        public Bitmap GetImage() {
            return bitmap;
        }
        public void SaveImage(string filename, ImageFormat format) {
            if (bitmap != null) {
                bitmap.Save(filename, format);
            }
        }

        /// <summary>
        /// Added by Steve Clements to make it a little easier to call!
        /// </summary>
        public static void DownloadAndSave(string imageUrl, string fileName, ImageFormat imageFormat) {
            var client = new DownloadImage(imageUrl);
            client.Download();
            client.SaveImage(fileName, imageFormat);
        }
    }
}
